const express = require('express');
const Todo = require('../models/Todo');
const auth = require('../middleware/auth');
const {
  successResponse,
  createdResponse,
  errorResponse,
  badRequestResponse,
  notFoundResponse
} = require('../utils/response');

const router = express.Router();

// 添加事项
router.post('/', auth, async (req, res) => {
  try {
    const { title, description, priority, dueDate } = req.body;

    // 验证必需的字段
    if (!title || title.trim() === '') {
      return badRequestResponse(res, '事项标题是必需的');
    }

    const todo = new Todo({
      title,
      description,
      priority,
      dueDate: dueDate ? new Date(dueDate) : undefined,
      user: req.user._id
    });

    await todo.save();

    createdResponse(res, '待办事项添加成功', todo);
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

// 获取事项列表
router.get('/', auth, async (req, res) => {
  try {
    const { page = 1, limit = 10, completed, priority, search } = req.query;
    
    // 构建查询条件
    const query = { user: req.user._id };
    
    if (completed !== undefined) {
      query.completed = completed === 'true';
    }
    
    if (priority) {
      query.priority = priority;
    }
    
    if (search) {
      query.$or = [
        { title: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } }
      ];
    }

    const todos = await Todo.find(query)
      .sort({ createdAt: -1 })
      .limit(limit * 1)
      .skip((page - 1) * limit);

    const total = await Todo.countDocuments(query);

    successResponse(res, '获取待办事项列表成功', {
      todos,
      totalPages: Math.ceil(total / limit),
      currentPage: page,
      total
    });
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

// 搜索事项
router.get('/search', auth, async (req, res) => {
  try {
    const { q, completed, priority } = req.query;
    
    if (!q) {
      return badRequestResponse(res, '搜索关键词不能为空');
    }

    const query = {
      user: req.user._id,
      $or: [
        { title: { $regex: q, $options: 'i' } },
        { description: { $regex: q, $options: 'i' } }
      ]
    };
    
    if (completed !== undefined) {
      query.completed = completed === 'true';
    }
    
    if (priority) {
      query.priority = priority;
    }

    const todos = await Todo.find(query).sort({ createdAt: -1 });

    successResponse(res, '搜索成功', todos);
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

// 获取单个事项
router.get('/:id', auth, async (req, res) => {
  try {
    const todo = await Todo.findOne({
      _id: req.params.id,
      user: req.user._id
    });

    if (!todo) {
      return notFoundResponse(res, '待办事项不存在');
    }

    successResponse(res, '获取待办事项成功', todo);
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

// 更新事项（完成或修改事项名）
router.patch('/:id', auth, async (req, res) => {
  try {
    const { title, description, completed, priority, dueDate } = req.body;
    
    const updateData = {};
    if (title !== undefined) updateData.title = title;
    if (description !== undefined) updateData.description = description;
    if (completed !== undefined) updateData.completed = completed;
    if (priority !== undefined) updateData.priority = priority;
    if (dueDate !== undefined) updateData.dueDate = dueDate ? new Date(dueDate) : null;

    const todo = await Todo.findOneAndUpdate(
      { _id: req.params.id, user: req.user._id },
      updateData,
      { new: true, runValidators: true }
    );

    if (!todo) {
      return notFoundResponse(res, '待办事项不存在');
    }

    successResponse(res, '待办事项更新成功', todo);
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

// 删除事项
router.delete('/:id', auth, async (req, res) => {
  try {
    const todo = await Todo.findOneAndDelete({
      _id: req.params.id,
      user: req.user._id
    });

    if (!todo) {
      return notFoundResponse(res, '待办事项不存在');
    }

    successResponse(res, '待办事项删除成功');
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

// 批量操作
router.patch('/bulk/update', auth, async (req, res) => {
  try {
    const { ids, completed } = req.body;
    
    if (!Array.isArray(ids) || ids.length === 0) {
      return badRequestResponse(res, '请提供有效的事项ID数组');
    }

    const result = await Todo.updateMany(
      { _id: { $in: ids }, user: req.user._id },
      { completed }
    );

    successResponse(res, `成功更新${result.modifiedCount}个待办事项`, { modifiedCount: result.modifiedCount });
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

// 批量删除事项
router.delete('/bulk/delete', auth, async (req, res) => {
  try {
    const { ids } = req.body;
    
    if (!Array.isArray(ids) || ids.length === 0) {
      return badRequestResponse(res, '请提供有效的事项ID数组');
    }

    const result = await Todo.deleteMany({
      _id: { $in: ids },
      user: req.user._id
    });

    successResponse(res, `成功删除${result.deletedCount}个待办事项`, { 
      deletedCount: result.deletedCount,
      deletedIds: ids.slice(0, result.deletedCount)
    });
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

module.exports = router; 